package com.mnt.washio.utils.network.ws;

import java.io.IOException;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.NetworkUtils;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;

@SuppressLint("SimpleDateFormat")
public class AddressWSControl extends BaseWSControl {
	public static boolean CREATE_ADDRESS = true;
	public static boolean UPDATE_ADDRESS = false;
	
	private String objectId;
	private String userId;
	private String firstAdd;
	private String secondAdd;
	private String zipCode;
	private String name;
	private String note;
	private boolean flag;

	public AddressWSControl(Context context,
			WebServiceCommunicatorListener listener, String userId, String objectId,
			String firstAdd, String secondAdd, String zipCode, String name, String note, boolean flag) {
		super(context, listener, WebServiceFlag.ADD_ADDRESS);
		this.objectId = objectId;
		this.userId = userId;
		this.firstAdd = firstAdd;
		this.secondAdd = secondAdd;
		this.zipCode = zipCode;
		this.name = name;
		this.note = note;
		this.flag = flag;
	}

	@Override
	protected Object doInBackground(Void... ps) {
		// Get local database
		String url = "";
		if(flag == CREATE_ADDRESS){
			url = Statics.ADMIN_WS_URL + "account/address/" + userId;
		}else{
			url = Statics.ADMIN_WS_URL + "account/address/" + objectId;
		}

		HashMap<String, String> params = new HashMap<String, String>();
		params.put("zip", zipCode);
		params.put("name", name);
		params.put("note", note);
		params.put("address", firstAdd);
		params.put("apartmentNumber", secondAdd);

		try {
			String respone = "";
			if(flag == CREATE_ADDRESS){
				respone = NetworkUtils.doPostRequest(url, params);
			}else{
				respone = NetworkUtils.doPutRequest(url, params, null);
			}
			try {
				JSONObject jsonObject = new JSONObject(respone);

				return jsonObject.getString("error");
			} catch (JSONException e) {
				return "Successful";
			}

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return mError;
	}

}
